package com.dayu.tcp.protocol;

import com.alibaba.fastjson2.JSON;
import com.dayu.tcp.conf.K1TcpConf;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class K1RestfulRequest implements Serializable {

    //请求序列号
    protected long sequence;

    //restful 服务名
    protected String serviceName;

    //restful 请求地址
    protected String url;

    //restful 请求方式 POST GET
    protected String method;

    //请求头部 json格式
    protected String headers;

    //请求参数 json格式
    protected String params;


    public static K1RestfulRequest k1BaseMessageTORequest(K1BaseMessage msg) {
        return JSON.parseObject(new String(msg.getRawData(), K1TcpConf.SYSTEM_CHARSET), K1RestfulRequest.class);
    }

    public static K1BaseMessage requestTOK1BaseMessage(K1RestfulRequest request) {
        String str = JSON.toJSONString(request);
        byte[] buf = str.getBytes(K1TcpConf.SYSTEM_CHARSET);
        K1BaseMessage ret = new K1BaseMessage();
        ret.setMagic(K1Protocol.MAGIC);
        ret.setVersion(K1Protocol.VERSION);
        ret.setMessageType(K1Protocol.MESSAGE_TYPE_RESTFUL_REQUEST);
        ret.setSequenceId(request.getSequence());
        ret.setSerializerType(K1Protocol.SERIALIZER_JSON);
        ret.setCompressType(K1Protocol.COMPRESS_NONE);
        ret.setEncryptType(K1Protocol.ENCRYPT_NONE);
        ret.setEmptyBytes(K1Protocol.EMPTY);
        ret.setRawDataLength(buf.length);
        ret.setRawData(buf);
        return ret;
    }
}
